/*
 * @lc app=leetcode.cn id=566 lang=javascript
 *
 * [566] 重塑矩阵
 */

// @lc code=start
/**
 * @param {number[][]} nums
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
var matrixReshape = function (nums, r, c) {
  let m = nums.length;
  let n = nums[0]?.length || 1;

  if (m * n !== r * c) {
    return nums;
  }

  const result = new Array(r).fill(0).map(() => new Array(c).fill(0));
  for (let i = 0; i < m * n; i++) {
    // (i,j) = i*n+j
    result[Math.floor(i / c)][i % c] = nums[Math.floor(i / n)][i % n];
  }

  return result;
};
// @lc code=end
